package com.sxhuayuan.parking.controller.admin;

import java.math.BigDecimal;
import java.time.LocalDate;

import javax.annotation.Resource;

import com.sxhuayuan.parking.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.ProfitStatistics;
import com.sxhuayuan.parking.service.ProfitStatisticsService;
import com.sxhuayuan.parking.task.ProfitStatisticsTask;
import com.sxhuayuan.parking.utils.DateUtils;

/**
 * 代理分润统计
 * 
 * @author 何龙
 * @create 2019-04-29 09:50
 */
@RestController(value = "adminProfitStatisticsController")
@RequestMapping("/admin/profitstatistics")
public class ProfitStatisticsController extends BaseController {

	Logger log = LoggerFactory.getLogger(ProfitStatisticsController.class);

	@Resource(name = "profitStatisticsServiceImpl")
	ProfitStatisticsService service;
	@Resource(name = "taskExecutor")
	TaskExecutor taskExecutor;

	@PostMapping("/list")
	public RespMessage list(@RequestBody Pageable pageable) {
		Agent agent = null;
		Page<ProfitStatistics> page = service.findPage(pageable, agent);
		return successResp(page);
	}

	/**
	 * 根据查询条件统计分润
	 * 
	 * @param pageable
	 *            分页查询条件
	 * @return 总分润 微信分润 支付宝分润
	 */
	@PostMapping("/sum/money")
	public RespMessage sumMoney(@RequestBody Pageable pageable) {
		BigDecimal[] bigDecimals = service.sumByPage(pageable, null);
		return successResp(bigDecimals);
	}

	@RequestMapping("/init")
	public RespMessage initProfitStatistics(String start, String end) {
		if (start == null || end == null) {
			return RespMessage.error("请传参数:start和end");
		}
		LocalDate startDate = LocalDate.parse(start);
		LocalDate endDate = LocalDate.parse(end);
		if (startDate.isAfter(endDate)) {
			return RespMessage.error("开始时间必须早于结束时间");
		}
		long diff = DateUtils.diff(startDate, endDate);
		for (int i = 0; i <= diff; i++) {
			LocalDate date = startDate.plusDays(i);
			log.debug("添加分润统计任务: {}", date);
			taskExecutor.execute(new ProfitStatisticsTask(date));
		}
		return RespMessage.success("已添加任务数:" + (diff + 1));
	}
}
